package com.bush.mall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.Assert;

import com.bush.mall.common.entity.Result;
import com.bush.mall.common.exception.SaaSException;
import com.bush.mall.product.mapper.CategoryMapper;
import com.bush.mall.product.entity.CategoryEntity;
import com.bush.mall.product.service.CategoryService;

/**
 * 商品三级分类
 * @author RUN
 * @date 2022-11-28
 */
@Service(CategoryService.BEAN_ID)
@Slf4j
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, CategoryEntity> implements CategoryService {



    /**
     * 添加商品分类表单对象
     * @author RUN
     * @date 2022-11-28
     */
    @Override
    public Result saveCategory(CategoryEntity category) {
        try{
            Assert.notNull(category,"参数异常");
            category.setSort(0);
            category.setShowStatus(1);
            boolean flag = this.save(category);
            if (flag) return Result.ok(category).success("商品分类添加成功");
            throw new SaaSException("商品分类添加失败");
        }catch(Exception e){
            log.error("CategoryService saveCategory ERROR => {}" , e.getMessage());
            return Result.error(e.getMessage());
        }
    }


    /**
     * 修改商品分类表单
     * @author RUN
     * @date 2022-12-01
     */
    @Override
    public Result updateCategory(CategoryEntity category) {
        try{
            Assert.notNull(category,"参数异常");
            boolean flag = this.updateById(category);
            if (flag) return Result.ok().success("商品分类修改成功");
            throw new SaaSException("商品分类修改失败");
        }catch(Exception e){
            log.error("CategoryService updateCategory ERROR => {}" , e.getMessage());
            return Result.error(e.getMessage());
        }
    }


    /**
     * 通过id删除商品三级分类表单
     * @author RUN
     * @date 2022-11-28
     */
    @Override
    public Result deleteCategory(Long id) {
        try{
            Assert.notNull(id,"参数异常");
            boolean flag = this.removeById(id);
            if (flag) return Result.ok().success("商品分类删除成功");
            throw new SaaSException("商品分类删除失败");
        }catch(Exception e){
            log.error("CategoryService deleteCategory ERROR => {}" , e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 树形查找分类列表
     * @return {@link Result}
     */
    @Override
    public Result tree() {
        try{
            List<CategoryEntity> list = baseMapper.selectList(
                    new LambdaQueryWrapper<CategoryEntity>()
                            .eq(CategoryEntity::getShowStatus,1)
            );

            List<CategoryEntity> nodes = list
                    .stream()
                    .filter(s -> s.getCatLevel() == 1)
                    .collect(Collectors.toList());

            for (CategoryEntity parentNode : nodes) {
                recursionCategoryTree(parentNode,list);
            }
            return Result.ok(nodes);
        }catch(Exception e){
            log.error(e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 根据商品类别id查询
     * @param id id
     * @return {@link Result}
     */
    @Override
    public Result queryByCategoryId(Long id) {
        try{
            Assert.notNull(id, "参数异常!");
            CategoryEntity entity = this.getById(id);
            return Result.ok(entity);
        }catch(Exception e){
            log.error(e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 通过指定ids批量删除商品分类
     * @param ids ids
     * @return {@link Result}
     */
    @Override
    public Result deleteBatchCategory(List<Long> ids) {
        try{
            Assert.notNull(ids,"参数异常");
            boolean flag = this.removeByIds(ids);
            if (flag) return Result.ok().success("商品分类删除成功");
            throw new SaaSException("商品分类删除失败");
        }catch(Exception e){
            log.error(e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 获取指定id三层分类
     * @param id id
     * @return {@link Result}
     */
    @Override
    public Result three(Long id) {
        try{
            Assert.notNull(id,"参数异常");
            long[] array = new long[3];
            CategoryEntity n0 = baseMapper.selectById(id);
            CategoryEntity n1 = baseMapper.selectById(n0.getParentCid());
            CategoryEntity n2 = baseMapper.selectById(n1.getParentCid());
            array[2] = id;
            array[1] = n1.getCatId();
            array[0] = n2.getCatId();
            return Result.ok(array);
        }catch(Exception e){
            log.error(e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 递归分类树
     * @param categoryEntity 类别实体
     * @param list           列表
     */
    private void recursionCategoryTree(CategoryEntity categoryEntity, List<CategoryEntity> list) {
        List<CategoryEntity> nodes = list
                .stream()
                .filter(s -> s.getParentCid().equals(categoryEntity.getCatId()))
                .collect(Collectors.toList());
        if (nodes.size() != 0){
            categoryEntity.setChildren(nodes);
            nodes.forEach( node -> recursionCategoryTree(node,list) );
        }
    }


}